package com.hongxun.design.activitys;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.PEnvironmentalAdapter;
import com.hongxun.design.bean.BackPhotosBean;
import com.hongxun.design.bean.BeforeExpItemBean;
import com.hongxun.design.bean.ChannelAListBean;
import com.hongxun.design.bean.ChannelListBean;
import com.hongxun.design.bean.EnvInfoBean;
import com.hongxun.design.bean.EnvInfoItemBean;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.PhotoBean;
import com.hongxun.design.bean.PhotoEnvironmentalItemBean;
import com.hongxun.design.bean.PhotoGraphBean;
import com.hongxun.design.bean.PhotoPassagewayBean;
import com.hongxun.design.bean.PhotoPassagewayItemBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.dragview.MyPassagewayDragView;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.myslider.MyBaseSliderView;
import com.hongxun.design.ui.myslider.MyTextSliderView;
import com.hongxun.design.ui.photographview.PhotoEnvironmentalDialog;
import com.hongxun.design.ui.voicerecorder.VoiceRecorder;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.clicklistener.NoDoubleClickListener;
import com.hongxun.design.utils.dragutil.DragUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.screenshotutil.ScreenShot;
import com.hongxun.design.utils.soundUtil.UPlayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zerdoor_pc on 2016/5/11.
 */
public class EditImageActivity extends BaseActivity implements HeadSecond, View.OnTouchListener {
    /**
     * 共有属性与控件*
     */
    private String path;
    private int code, type;
    private String title;
    SimpleDraweeView editimage_image;
    HeadSecondControlPanel headsecond_layout;
    String PHOTO_ID, PHOTO_UUID;
    private Handler delectHander;
    View line;
    String newPath = "";
    SliderLayout slider;
    boolean f = false;//防止重复点击保存
    /**
     * 位置风格的属性与控件*
     */
    SimpleDraweeView editimage_move_icon;
    RelativeLayout editimage_move;//单个拖拽控件
    private Handler beforeExpHandler;
    private Handler channelAListHandler;
    private Handler channelListHandler;
    PEnvironmentalAdapter madapter;
    /**
     * 通道风格的属性与控件*
     */
    MyPassagewayDragView passageway;
    PhotoPassagewayBean passagewayBean;

    boolean Drag = true;
    /**
     * 环境风格的属性与控件*
     */
    PhotoEnvironmentalDialog environmental;
    PhotoGraphBean bean;
    private Handler envInfoHandler;
    private Handler saveEnvHandler;
    String environment_id;
    List<PhotoEnvironmentalItemBean> environmentalBean;
    //public static List<ImageTextItem> imageTextItems=new ArrayList<>();

    String exploration_id = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editimage);
        TAG = "EditImageActivity";
        exploration_id = MyApp.currExploration.getExploration_id();
        findBar();
        findView();
        initialization();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getData();
    }

    @Override
    protected void onStart() {
        mActivity = this;
        super.onStart();
    }

    @Override
    protected void onResume() {
        MyApp.activity = this;
        mActivity = this;
        super.onResume();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private void getData() {
        Bundle bundle = getIntent().getExtras();
        path = bundle.getString(MString.PATH);
        code = bundle.getInt(MString.CODE);
        type = bundle.getInt(MString.ISEDIT);
        if (type == Constant.EDIT) {
            PHOTO_ID = bundle.getString(MString.PHOTO_ID);
            PHOTO_UUID = bundle.getString(MString.PHOTO_UUID);
        }
        //bundle.putInt(MString.ISEDIT, Constant.EDIT);
        switch (code) {
            case Constant.TypePosition:
                title = MString.Position;
                break;
            case Constant.TypePassageway:
                title = MString.Passageway;
                if (type == Constant.CREATE) {
                    title = MString.Passageway_edit;
                }
                break;
            case Constant.TypeEnvironmental:
                title = MString.Environmental;
                if (type == Constant.CREATE) {
                    title = MString.Environmental_edit;
                }
                break;
        }
        if (path.length() == 0) {
            path = MString.LOCALIMAGEHEAD + R.mipmap.zhanweizhenfang;
            String json = bundle.getString(MString.Photos, "");
            bean = FastJsonUtil.JsonToData_Photos(json);
            //  bundle.putString(MString.Photos, JSON.toJSONString(photoGraphBean));
        }
    }

    @Override
    public void findBar() {
        getData();
        headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.editimage_title);
        line = findViewById(R.id.editimage_line);
        if (type == Constant.EDIT) {
            headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.delate, View.VISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.white, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        } else {
            if (code == Constant.TypePassageway) {
                headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, ListenerSet.back, title, R.color.bar_right, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
            } else {
                headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, View.VISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.bar_right, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
            }
        }
        if (MyApp.ReadOnly) {
            headsecond_layout.mRightTitle.setVisibility(View.INVISIBLE);
        }
        headsecond_layout.setClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!f) {
                    f = true;
                    switch (code) {
                        case Constant.TypePosition:
                            if (type == Constant.EDIT) {
                                delectPhotos();
                            } else {
                                headsecond_layout.setVisibility(View.GONE);
                                line.setVisibility(View.GONE);
                                MyDialog.Loading(mActivity);
                                newPath = ScreenShot.addclick(mActivity);//截屏
                                MyDialog.Close();
                                headsecond_layout.setVisibility(View.VISIBLE);
                                line.setVisibility(View.VISIBLE);
                                finish();
                            }
                            break;
                        case Constant.TypePassageway:
                            if (type == Constant.EDIT) {
                                delectPhotos();
                            } else {
                                finish();
                            }
                            break;
                        case Constant.TypeEnvironmental:
                            if (type == Constant.EDIT) {
                                delectPhotos();
                            } else {
                                addSaveEnvHandler();
                                PhotoEnvironmentalItemBean bean = madapter.getData().get(madapter.mPosition);
                                if (MyApp.isOnLine) {
                                    if (bean.getPath().length() > 0) {
                                        File file = new File(bean.getPath());
                                        if (file.exists()) {
                                            //上传录音
                                            String path = MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
                                            MyApp.File.copyFile(bean.getPath(), path);

                                            MyLog.L(MString.SUCCESSED + " copyFileto=" + path);
                                            MyApp.HTTP.sendFile(proHandler, HttpStringUtil.SUCCESSED, file, MString.PROJECT_RADIO);
                                        } else {
                                            //上传文件

                                            f = MyApp.HTTP.SaveEnv(saveEnvHandler, HttpStringUtil.SUCCESSED, environmentalBean);
                                        }
                                    } else {
                                        //上传文件
                                        f = MyApp.HTTP.SaveEnv(saveEnvHandler, HttpStringUtil.SUCCESSED, environmentalBean);
                                    }
                                } else {
                                    //保存语音并缓存数据
                                    //离线时移动录音到缓存
                                    //缓存数据
                                    Map<String, Object> map = MyApp.HTTP.SaveEnv(environmentalBean);
                                    if (map != null) {
                                        File file = new File(bean.getPath());
                                        if (file.exists()) {
                                            String path = MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
                                            String path2 = MyApp.File.getCachaPhotoVoiceRequestPath() + "voice.amr";
                                            MyApp.File.copyFile(bean.getPath(), path);
                                            MyApp.File.copyFile(bean.getPath(), path2);
                                            map.put(MString.voice_remark, path);
                                            SetFileUtil.setEnvInfo(map);
                                            map.put(MString.voice_remark, "voice.amr");
                                            SetFileUtil.setEnvRInfo(map);
                                        } else {
                                            SetFileUtil.setEnvInfo(map);
                                            SetFileUtil.setEnvRInfo(map);
                                        }
                                        finish();
                                    }
                                }

                            }
                            break;

                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (newPath.length() != 0) {//保存图片
            Message msg = new Message();
            msg.what = 2;
            msg.obj = newPath;
            PhotoGraphActivity.savePhotoHandler.sendMessage(msg);
            newPath = "";
        }
        bean = null;
        environmentalBean = null;
        madapter = null;
        editimage_image = null;

        super.onDestroy();
    }

    /**
     * 删除照片*
     */
    private void delectPhotos() {
        addDelectHander();
        if (MyApp.isOnLine) {
            if (PHOTO_ID != null && PHOTO_ID.length() > 0 && !PHOTO_ID.equals(MString.code_zero)) {
                boolean isInt = true;
                try {
                    Integer.parseInt(PHOTO_ID);
                } catch (Exception e) {
                    isInt = false;
                }
                if (isInt) {
                    MyApp.HTTP.DelExpPhoto(delectHander, HttpStringUtil.SUCCESSED, PHOTO_ID);
                } else {
                    delData();
                }
            } else {
                delData();
            }
        } else {
            delData();
        }
    }

    private void delData() {
        //缓存中删除
        MyApp.File.delect(path);
        //删除提交数据里面的照片
        if (path.contains("/")) {
            String picname = path.substring(path.lastIndexOf("/") + 1);
            String reqpath = MyApp.File.getCachaPhotoRequestPath() + "2/" + picname;
            MyApp.File.delect(reqpath);
        }
        delectHander.sendEmptyMessage(1);
    }


    private void addDelectHander() {
        delectHander = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        delectHander.sendEmptyMessage(1);
                        break;
                    case 1:
                        PhotoGraphActivity.setUpdate(code, path);//删除
                        finish();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    @Override
    protected void findView() {
        /**公用控件初始化**/
        editimage_image = (SimpleDraweeView) findViewById(R.id.editimage_image);
        switch (code) {
            case Constant.TypePosition:
                findView_Position();
                break;
            case Constant.TypePassageway:
                findView_Passageway();
                break;
            case Constant.TypeEnvironmental:
                findView_Environmental();
                break;
        }
        super.findView();
    }

    @Override
    protected void initialization() {
        super.initialization();
    }

    /**
     * ****************************位置拍照相关方法*********************************************************************
     */
    private void findView_Position() {
        editimage_move = (RelativeLayout) findViewById(R.id.editimage_move);
        MyLog.L(MString.SUCCESSED + "  path=" + path);
        editimage_image.setImageURI(UriUtil.getUrl(path, code));
        if (type == Constant.CREATE) {
            editimage_move_icon = (SimpleDraweeView) findViewById(R.id.editimage_move_icon);
            editimage_move_icon.setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + MyApp.currExploration.getIcon()));
            editimage_move.setVisibility(View.VISIBLE);
            DragUtil dragUtil = new DragUtil(this, editimage_move);//设置拖拽属性
            dragUtil.setDrag();
        } else {
            editimage_move.setVisibility(View.GONE);
        }

    }

    /**
     * ****************************通道拍照相关方法*********************************************************************
     */
    private void findView_Passageway() {
        RelativeLayout editimage_passageway = (RelativeLayout) findViewById(R.id.editimage_passageway);
        if (type == Constant.CREATE) {
            editimage_passageway.setVisibility(View.VISIBLE);
            passageway = (MyPassagewayDragView) findViewById(R.id.passageway);
            passagewayBean = DataUtil.getPhotoPassagewayBean();
            passageway.setRight(MyApp.currExploration.getNumber(), null);
            /**匹配轮播控件**/
            slider = (SliderLayout) findViewById(R.id.editimage_slider_passageway);
            addSlider();
            getBeforeExp();//获取定位点上级定位点
        } else {
            editimage_passageway.setVisibility(View.GONE);
            editimage_image.setImageURI(UriUtil.getUrl(path, code));
        }
    }


    /**
     * 获取定位点上级定位点*
     */
    private void getBeforeExp() {
        addBeforeExpHandler();
        if (MyApp.isOnLine) {
            MyApp.HTTP.getBeforeExp(beforeExpHandler, HttpStringUtil.SUCCESSED, exploration_id);
        } else {
            beforeExpHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, GetFileUtil.getBeforeExp(MyApp.currExploration)));
        }
    }

    /**
     * 定位点上级定位点信息接受handler*
     */

    private void addBeforeExpHandler() {
        beforeExpHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        MyLog.L(MString.SUCCESSED + " MyApp.currExploration.getDistance()===" + MyApp.currExploration.getDistance());
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            // MyApp.File.SaveFileData(MyApp.currProject.getStage_id(), MString.ProjectExploreAcrossBeforePoint + "_" + exploration_id, (String) msg.obj, "");
                            if (MyApp.isOnLine) {
                                SetFileUtil.setBeforeExp((String) msg.obj);//保存到缓存
                            }
                            BeforeExpItemBean data = FastJsonUtil.JsonToGetExploration_Id((String) msg.obj);
                            MyLog.L(MString.SUCCESSED + " BeforeExpItemBean=" + JSON.toJSONString(data));
                            if (data != null) {
                                Drag = true;
                                passageway.setLeft(data.number, null);
//                                if (data.distance != null) {
//                                    try {
//                                        passageway.setDistance(Float.parseFloat(data.distance));
//                                    } catch (Exception e) {
//                                    }
//
//                                } else {
//                                    passageway.setDistance(0);
//                                }
                                String s = MyApp.currExploration.getDistance();

                                if (s.length() != 0) {
                                    MyLog.L(MString.SUCCESSED + " Distance========" + s);
                                    passageway.setDistance(Float.parseFloat(s));
                                } else if (data.getDistance() != null && data.getDistance().length() > 0) {
                                    MyLog.L(MString.SUCCESSED + " Distance========" + s);
                                    passageway.setDistance(Float.parseFloat(data.getDistance()));
                                } else {
                                    ToastShow.showShort(mActivity, "获取档距失败！");
                                    MyLog.L(MString.SUCCESSED + " Distance========" + 0);
                                }

                                getChannelList(data.getBefore_exp_id());//通道特征点(无下级)列表
                                getChannelAList();//通道特征点(有下级)列表
//                              http://192.168.1.61:8088/upload/pic/20160531/1464681614402.amr/
                            } else {
                                passageway.setLeft("无", null);
                                Drag = false;
                                passageway.setData(passagewayBean, Drag);//加载
                            }
                        } else if (msg.obj.toString().length() == 0) {
                            passageway.setLeft("无", null);
                            Drag = false;
                            passageway.setData(passagewayBean, Drag);//加载
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:
                        break;
                    case HttpStringUtil.ERROR:
//                        String pointJson = MyApp.File.ReadFileData(MString.ProjectExploreAcrossBeforePoint + "_" + exploration_id);
//                        if (pointJson != null && pointJson.length() > 0) {
//                            beforeExpHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, pointJson));
//                        }
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        //MyApp.File.ReadFileToSend(beforeExpHandler, MString.ProjectExploreAcrossBeforePoint + "_" + exploration_id);
                        break;
                }
            }
        };
    }


    /**
     * 通道特征点（无上级）列表*
     */
    private void getChannelList(String befor) {
        addChannelListHandler();
        if (MyApp.isOnLine) {
            MyApp.HTTP.getChannelList(channelListHandler, HttpStringUtil.SUCCESSED, befor);
        } else {
//            passageway.setData(passagewayBean, Drag);
            channelListHandler.sendEmptyMessage(1);
//
            //GetFileUtil.getExplorationList()
        }
    }

    /**
     * 通道特征点（无上级）列表handler*
     */
    private void addChannelListHandler() {
        channelListHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            List<ChannelListBean> data = FastJsonUtil.JsonToGetChannelList((String) msg.obj);
                            //加载上部图标数据
                            List<PhotoPassagewayItemBean> list = new ArrayList<>();
                            for (ChannelListBean c : data) {
                                DataUtil.addPassItem(c, list);
                            }
                            passagewayBean.setScrollData(list);
                            passageway.setData(passagewayBean, Drag);
                        } else {
                            passageway.setData(passagewayBean, Drag);
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1://遍历列表上联下的特征点并过滤掉存在的点
                        try {
                            List<Exploration> list = GetFileUtil.getExplorationList(MyApp.currExploration.getPoint_type());
                            if (list == null || list.size() == 0 || MyApp.currExploration.getBefore_exp().length() == 0) {
                                passageway.setData(passagewayBean, Drag);
                                return;
                            }
                            //存在上联
                            Exploration befor = null;
                            for (Exploration e : list) {
                                if ((e.getExploration_id().length() > 0 && e.getExploration_id().equals(MyApp.currExploration.getBefore_exp())) || (e.getUuid().length() > 0 &&
                                        e.getUuid().equals(MyApp.currExploration.getBefore_exp()))) {
                                    //上联
                                    befor = e;
                                    break;
                                }
                            }
                            if (befor == null) {
                                passageway.setData(passagewayBean, Drag);
                                return;
                            } else {
                                List<Exploration> cList = new ArrayList<>();
                                for (Exploration e : list) {
                                    if (e.getBefore_exp().length() > 0 && (e.getBefore_exp().equals(befor.getExploration_id()) || e.getBefore_exp().equals(befor.getUuid()))) {
                                        //上联
                                        cList.add(e);
                                    }
                                }

                                if (cList != null && cList.size() > 0) {
                                    String s = GetFileUtil.getChannelList(MyApp.currExploration);
                                    if (s == null || s.length() == 0) {
                                        passageway.setData(passagewayBean, Drag);
                                        return;
                                    }
                                    List<Exploration> cList2 = new ArrayList<>();
                                    cList2.addAll(cList);
                                    List<ChannelAListBean> data = FastJsonUtil.JsonToGetChannelAList(s);
                                    if (data != null && data.size() > 0) {
                                        for (Exploration e : cList) {
                                            for (ChannelAListBean c : data) {
                                                if (c.getExploration_id() != null && c.getExploration_id().length() > 0 && (c.getExploration_id().equals(e.getUuid()) || c.getExploration_id().equals(e.getExploration_id()))) {
                                                    cList2.remove(e);
                                                }
                                            }
                                        }
                                    }
                                    List<PhotoPassagewayItemBean> beanList = new ArrayList<>();
                                    for (Exploration c : cList2) {
                                        DataUtil.addPassItem(c, beanList);
                                    }
                                    passagewayBean.setScrollData(beanList);
                                    passageway.setData(passagewayBean, Drag);
                                } else {
                                    passageway.setData(passagewayBean, Drag);
                                    return;
                                }


                            }

                        } catch (Exception e) {
                            passageway.setData(passagewayBean, Drag);
                            return;
                        }
                        break;
                    case HttpStringUtil.ERROR:
//                        String pointJson = MyApp.File.ReadFileData(MString.ProjectExploreAcrossBeforePointChannelList + "_" + exploration_id);
//                        if (pointJson != null && pointJson.length() > 0) {
//                            channelListHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, pointJson));
//                        }
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        //MyApp.File.ReadFileToSend(channelListHandler, MString.ProjectExploreAcrossBeforePointChannelList + "_" + exploration_id);
                        break;
                }
            }
        };
    }


    /**
     * 通道特征点(有下级)列表*
     */
    private void getChannelAList() {
        addChannelAListHandler();
        if (MyApp.isOnLine) {
            MyApp.HTTP.getChannelAList(channelAListHandler, HttpStringUtil.SUCCESSED, exploration_id);
        } else {
            channelAListHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, GetFileUtil.getChannelList(MyApp.currExploration)));
        }
    }

    /**
     * 通道特征点(有下级)列表handler*
     */
    private void addChannelAListHandler() {
        channelAListHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (MyApp.isOnLine) {
                                SetFileUtil.setChannelList((String) msg.obj);
                            }
                            List<ChannelAListBean> data = FastJsonUtil.JsonToGetChannelAList((String) msg.obj);
                            if (data != null && data.size() > 0) {
                                List<PhotoPassagewayItemBean> list = new ArrayList<>();
                                for (ChannelAListBean a : data) {
                                    if (!a.getFlag().equals(MString.del)) {
                                        DataUtil.addPassItem(a, list);
                                    }
                                }
                                passageway.addViews(list);

                            }
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:

                        break;
                    case HttpStringUtil.ERROR:
//                        String pointJson = MyApp.File.ReadFileData(MString.ProjectExploreAcrossOnChannelList + "_" + exploration_id);
//                        if (pointJson != null && pointJson.length() > 0) {
//                            channelAListHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, pointJson));
//                        }
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        // MyApp.File.ReadFileToSend(channelAListHandler, MString.ProjectExploreAcrossOnChannelList + "_" + exploration_id);
                        break;
                }
            }
        };
    }


    /**
     * ****************************环境拍照相关方法*********************************************************************
     */
    private void findView_Environmental() {
        RelativeLayout editimage_environmental = (RelativeLayout) findViewById(R.id.editimage_environmental);
        if (type == Constant.CREATE) {
            editimage_environmental.setVisibility(View.VISIBLE);//显示风格
            /**找到属性控件并匹配**/
            environmental = (PhotoEnvironmentalDialog) findViewById(R.id.environmental);
            /**匹配轮播控件**/
            slider = (SliderLayout) findViewById(R.id.editimage_slider);
            addSlider();
            setHandler();//录音音量handler
            findViewOfVoice();//录音控件初始化
            addProHandler();//加载语音上传监听器
            environmentalBean = DataUtil.getEnvironmentalBean();//得到适配属性数据
            madapter = environmental.setListview(environmentalBean, this);
            getEnvInfo();//请求数据
        } else {
            editimage_environmental.setVisibility(View.GONE);
            editimage_image.setImageURI(UriUtil.getUrl(path, code));
        }
    }

    /**
     * 获取环境信息*
     */
    private void getEnvInfo() {
        addEnvInfoHandler();
        if (MyApp.isOnLine) {
            MyApp.HTTP.getEnvInfo(envInfoHandler, HttpStringUtil.SUCCESSED, exploration_id);
        } else {
            //获取缓存数据
            envInfoHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, GetFileUtil.getEnvInfo(MyApp.currExploration)));
        }
    }

    /**
     * 加载环境信息接受handler*
     */
    private void addEnvInfoHandler() {
        envInfoHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            //MyApp.File.SaveFileData(MyApp.currProject.getStage_id(), MString.ProjectExploreEnvInfo + "_" + exploration_id, (String) msg.obj, "no");
                            EnvInfoBean bean = FastJsonUtil.JsonToGetEnvInfo((String) msg.obj);
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(bean));
                            if (bean.envInfo == null) {
//                                envInfoHandler.sendEmptyMessage(1);
                                MyLog.L(MString.SUCCESSED + "空");
                            } else {
                                MyLog.L(MString.SUCCESSED + "不为空");
                                EnvInfoItemBean itemBean = bean.envInfo;
                                environment_id = itemBean.environment_id;
//                                判断语音并下载
                                String path = MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
                                String sourse = itemBean.voice_remark;
                                if (sourse != null && sourse.length() > 0 && MyApp.isOnLine)
                                    path = MyApp.getHttpVoice(sourse, path);
                                itemBean.voice_remark = path;

                                if (environmentalBean == null) {
                                    environmentalBean = DataUtil.getEnvironmentalBean(itemBean.traffic, itemBean.width, itemBean.haul_distance, itemBean.characters_remark, itemBean.voice_remark);
                                } else {
                                    environmentalBean.clear();
                                    environmentalBean.addAll(DataUtil.getEnvironmentalBean(itemBean.traffic, itemBean.width, itemBean.haul_distance, itemBean.characters_remark, itemBean.voice_remark));
                                }
                                envInfoHandler.sendEmptyMessage(2);
                            }
                        }
                        break;
                    case 1:
                        environmentalBean = DataUtil.getEnvironmentalBean();//得到适配属性数据
                        envInfoHandler.sendEmptyMessage(2);
                        break;
                    case 2:

                        if (madapter == null) {
                            madapter = environmental.setListview(environmentalBean, mActivity);
                        } else {
                            MyLog.L(MString.SUCCESSED + "不为空" + JSON.toJSONString(environmentalBean));
                            madapter.setBeanList(environmentalBean);
                        }
                        break;
                    case HttpStringUtil.ERROR:
//                        String pointJson = MyApp.File.ReadFileData(MString.ProjectExploreEnvInfo + "_" + exploration_id);
//                        if (pointJson != null && pointJson.length() > 0) {
//                            envInfoHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, pointJson));
//                        }
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        // MyApp.File.ReadFileToSend(envInfoHandler, MString.ProjectExploreEnvInfo + "_" + exploration_id);
                        break;
                }
            }
        };
    }

    /**
     * 保存环境信息*
     */
    private void addSaveEnvHandler() {
        if (saveEnvHandler == null) saveEnvHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            Map<String, Object> map = MyApp.HTTP.SaveEnv(environmentalBean);
                            PhotoEnvironmentalItemBean bean = madapter.getData().get(madapter.mPosition);
                            if (bean.getPath().length() > 0) {
                                String path = MyApp.File.getCachaPhotoVoicePath() + "voice.amr";
                                map.put(MString.voice_remark, path);
                            }
                            SetFileUtil.setEnvRInfo(map);
                            saveEnvHandler.sendEmptyMessage(1);
                        } else {
                            f = false;
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:
                        finish();
                        break;
                    case HttpStringUtil.ERROR:
                        f = false;
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /**
     * 查询踏勘照片*
     */
    private Handler getExpPhotoListHandler;

    private void addgetExpPhotoListHandler() {
        getExpPhotoListHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
//                            {"twoPhoto":{"photoNum":0,"photoList":[]},"threePhoto":{"photoNum":0,"photoList":[]},"onePhoto":{"photoNum":0,"photoList":[]}}
                            BackPhotosBean photosBean = FastJsonUtil.JsonToData_BackPhotos((String) msg.obj);
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(bean));
                            if (photosBean != null) {
                                String num = "";
                                if (Constant.TypeEnvironmental == code) {
                                    num = photosBean.threePhoto.photoNum + "";
                                    if (!num.equals("0")) {
                                        bean = new PhotoGraphBean(Constant.TypeEnvironmental, MString.Environmental, "记录环境影响因素",
                                                " ", -1, "", DataUtil.getPhotos_List(photosBean.threePhoto.photoList, Constant.TypeEnvironmental), null, null);
                                    }
                                } else {
                                    num = photosBean.twoPhoto.photoNum + "";
                                    if (!num.equals("0")) {
                                        bean = new PhotoGraphBean(Constant.TypePassageway, MString.Passageway, "转身拍摄通道信息",
                                                " ", -1, "", DataUtil.getPhotos_List(photosBean.twoPhoto.photoList, Constant.TypePassageway), null, null);
                                    }
                                }
                                if (bean == null) {
                                    addCarouselItem(null);
                                } else {

                                    addCarouselItem(bean.getPhotos());
                                }
                            }


                        }
                        break;
                    case 1:

                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }

    /*******************************拍照通用相关方法**********************************************************************/
    /**
     * 加载轮播*
     */
    private void addSlider() {
        if (bean != null) {
            addCarouselItem(bean.getPhotos());
        } else {
            //获取相片
            addgetExpPhotoListHandler();
            if (MyApp.isOnLine) {
                MyApp.HTTP.getExpPhotoList(getExpPhotoListHandler, HttpStringUtil.SUCCESSED, exploration_id);
            } else {
                BackPhotosBean b = GetFileUtil.getExplorationPhoto();
                if (b != null) {
                    String num = "";
                    if (Constant.TypeEnvironmental == code) {
                        num = b.threePhoto.photoNum + "";
                        if (!num.equals("0")) {
                            bean = new PhotoGraphBean(Constant.TypeEnvironmental, MString.Environmental, "记录环境影响因素",
                                    " ", -1, "", DataUtil.getPhotos_List(b.threePhoto.photoList, Constant.TypeEnvironmental), null, null);
                        }
                    } else {
                        num = b.twoPhoto.photoNum + "";
                        if (!num.equals("0")) {
                            bean = new PhotoGraphBean(Constant.TypePassageway, MString.Passageway, "转身拍摄通道信息",
                                    " ", -1, "", DataUtil.getPhotos_List(b.twoPhoto.photoList, Constant.TypePassageway), null, null);
                        }
                    }
                    if (bean == null) {
                        addCarouselItem(null);
                    } else {
                        addCarouselItem(bean.getPhotos());
                    }
                } else {
                    addCarouselItem(null);
                }


            }
//            addCarouselItem(null);
        }
    }

    private void addCarouselItem(List<PhotoBean> photos) {
        if (photos == null) {
            photos = new ArrayList<>();
            photos.add(new PhotoBean(type, null, ""));
        }
        MyLog.L(MyApp.AppName + "jsonjson List<PhotoBean>2==" + JSON.toJSONString(photos));
        for (PhotoBean home : photos) {
            MyTextSliderView textSliderView = new MyTextSliderView(this);
            String imageUrl = UriUtil.getUrlpath(home.getUrl(), code);
            MyLog.L(MyApp.AppName + "jsonjson imageUrl==" + imageUrl);
            if (imageUrl.length() == 0)
                imageUrl = MString.LOCALIMAGEHEAD + R.mipmap.zhanweizhenfang;
            final String finalImageUrl = imageUrl;
            textSliderView.description("")
                    .setHasTitle(false)
                    .image(imageUrl)
                    .error(R.mipmap.zhanweizhenfang)
                    .setScaleType(MyBaseSliderView.ScaleType.FitCenterCrop)
                    .setOnSliderClickListener(new MyBaseSliderView.OnSliderClickListener() {
                        @Override
                        public void onSliderClick(MyBaseSliderView slider) {
                            if (!finalImageUrl.contains(MString.LOCALIMAGEHEAD)) {
                                Bundle bundle = new Bundle();
                                bundle.putString(MString.PATH, finalImageUrl);
                                IntentToActivity.intent(mActivity, ShowBigImageActivity.class, bundle);
                            }
                        }
                    });

            slider.addSlider(textSliderView);
        }

        slider.setPresetTransformer(SliderLayout.Transformer.Default);//动画
        slider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        if (photos.size() == 1) {
            slider.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Invisible);
        } else {
            slider.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Visible);
        }
        slider.stopAutoCycle();
        slider.setCurrentPosition(0);
    }


    /**
     * 语音相关属性*
     */

    private LinearLayout voice_rcd_hint_loading,
            voice_rcd_hint_tooshort;
    private RelativeLayout voice_rcd_hint_rcding;
    private View rcChat_popup;
    VoiceRecorder voiceRecorder;
    private LinearLayout del_re, my_voice;
    private ImageView volume;
    Handler handler;
    public static boolean btn_vocie = false;
    private int flag = 1;
    private long startVoiceT, endVoiceT;
    private boolean isShosrt = false;
    private String openid;
    private int[] micImages = new int[]{R.mipmap.amp1,
            R.mipmap.amp2,
            R.mipmap.amp3,
            R.mipmap.amp4,
            R.mipmap.amp5,
            R.mipmap.amp6,
            R.mipmap.amp7,
    };

    private void findViewOfVoice() {
        volume = (ImageView) this.findViewById(R.id.volume);//音量
        voice_rcd_hint_rcding = (RelativeLayout) this
                .findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_tooshort);
        rcChat_popup = this.findViewById(R.id.rcChat_popup);
        del_re = (LinearLayout) this.findViewById(R.id.del_re);//取消
        my_voice = (LinearLayout) this.findViewById(R.id.my_voice);//录制
        voiceRecorder = new VoiceRecorder(handler);
        openid = "";
    }

    /**
     * 录音handler*
     */
    private void setHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                volume.setImageResource(micImages[msg.what / 2]);
            }
        };
    }

    private final int SPEECH = 1;
    float time;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        MyLog.L("listdatalistdatalistdata:onTouch3");
        MyLog.L(MyApp.AppName + "进入：" + event);
        if (!Environment.getExternalStorageDirectory().exists()) {
            ToastShow.showShort(this, "No SDCard");
            return false;
        }
        if (btn_vocie) {
            int[] location = new int[2];
            //if (view!=null)view.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
            int btn_rc_Y = location[1];
            int btn_rc_X = location[0];
            int[] del_location = new int[2];
            del_re.getLocationInWindow(del_location);
            int del_Y = del_location[1];
            int del_x = del_location[0];
            if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
                if (!Environment.getExternalStorageDirectory().exists()) {
                    ToastShow.showShort(this, "No SDCard");
                    return false;
                }
                if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {
                    //判断手势按下的位置是否是语音录制按钮的范围内
                    //mBtnRcd.setBackgroundResource(R.drawable.radius_social_chat_voice);//语音录制开始
                    //mBtnRcd.setText("松开发送");
                    rcChat_popup.setVisibility(View.VISIBLE);
                    voice_rcd_hint_loading.setVisibility(View.VISIBLE);
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    voice_rcd_hint_tooshort.setVisibility(View.GONE);
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            if (!isShosrt) {
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding
                                        .setVisibility(View.VISIBLE);
                            }
                        }
                    }, 300);
                    del_re.setVisibility(View.GONE);
                    my_voice.setVisibility(View.VISIBLE);
                    startVoiceT = System.currentTimeMillis();

                    try {
                        voiceRecorder.startRecording(null, openid, getApplicationContext());
                    } catch (Exception e) {
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                    }
                    flag = 2;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成
                //mBtnRcd.setBackgroundResource(R.drawable.radius_social_chat_voice_none);
                //mBtnRcd.setText("按住说话");
                if (del_re.getVisibility() == View.VISIBLE) {
                    rcChat_popup.setVisibility(View.GONE);
                    del_re.setVisibility(View.GONE);
                    my_voice.setVisibility(View.VISIBLE);
                    flag = 1;
                    if (voiceRecorder != null) {
                        File file = new File(voiceRecorder.getVoiceFilePath());
                        voiceRecorder.discardRecording();
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                } else {
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    endVoiceT = System.currentTimeMillis();// SystemClock.currentThreadTimeMillis();
                    flag = 1;
                    time = (float) ((endVoiceT - startVoiceT) / 1000);
                    if (time < 1) {

                        //Log.i("", "环信===时间短");
                        isShosrt = true;
                        voice_rcd_hint_loading.setVisibility(View.GONE);
                        voice_rcd_hint_rcding.setVisibility(View.GONE);
                        voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
                        if (voiceRecorder != null) {
                            File file = new File(voiceRecorder.getVoiceFilePath());
                            voiceRecorder.discardRecording();
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                voice_rcd_hint_tooshort
                                        .setVisibility(View.GONE);
                                rcChat_popup.setVisibility(View.GONE);

                                isShosrt = false;
                            }
                        }, 100);
                        btn_vocie = false;
                        //Log.i("", "环信===时间短返回");
                        return false;
                    }


                    int length = voiceRecorder.stopRecoding();
                    if (length > 0) {

                        btn_vocie = false;
                        //MyApp.HTTP.sendFile(proHandler, HttpStringUtil.SUCCESSED, new File(voiceRecorder.getVoiceFilePath()), MString.PROJECT_RADIO);
                        String path = voiceRecorder.getVoiceFilePath();
                        if (madapter.speechHolder != null) {
                            PhotoEnvironmentalItemBean bean = madapter.getData().get(madapter.mPosition);
                            madapter.speechHolder.speech_button.setVisibility(View.GONE);
                            madapter.speechHolder.speech_play_button.setVisibility(View.VISIBLE);
                            bean.setPath(path);
                            double t = (double) UPlayer.getIntence(path).getDuration() / (double) 1000;
                            bean.setValue(t + "");
                            madapter.notifyDataSetChanged();
                        }
                    }
                }
            }
            if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
                del_re.setVisibility(View.VISIBLE);
                my_voice.setVisibility(View.GONE);
                btn_vocie = false;
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                }

                if (voiceRecorder != null)
                    voiceRecorder.discardRecording();
            } else {
                del_re.setVisibility(View.GONE);
                my_voice.setVisibility(View.VISIBLE);

            }
        }
        return super.onTouchEvent(event);
    }

    private Handler proHandler;

    /**
     * 上传语音*
     */
    private void addProHandler() {
        proHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String path = FastJsonUtil.JsonToPath((String) msg.obj);
                            MyLog.L(MString.SUCCESSED + "path：" + path);
                            PhotoEnvironmentalItemBean bean = madapter.getData().get(madapter.mPosition);
                            bean.setPath(path);
                            f = MyApp.HTTP.SaveEnv(saveEnvHandler, HttpStringUtil.SUCCESSED, environmentalBean);
                        } else {
                            f = false;
                        }
                        break;
                    case SPEECH:

                        break;
                    case HttpStringUtil.ERROR:
                        f = false;
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;

                }
            }
        };
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        MyLog.L("listdatalistdatalistdata:onTouch2");
        if (btn_vocie) {
            onTouchEvent(motionEvent);

        }
        return false;
    }


}
